<template>
    <div class="bigBox">
        <!-- 基本信息录入开始 -->
        <div class="baseInfo">
            <div class="firHeader">
                <p>{{ title }}</p>
            </div>
            <el-divider></el-divider>
            <div class="contentArea">
                <div class="baseInfo-toView">
                    <el-row :gutter="24" class="content">
                        <el-form ref="elForm" :model="formData" :rules="baseRules" size="medium" label-width="100px">
                            <el-col :span="12">
                                <el-form-item label="框架编号" prop="planCode">
                                    <el-input v-model="formData.planCode" placeholder="系统自动生成" disabled clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="框架名称" prop="planName">
                                    <el-input v-model="formData.planName" placeholder="请输入计划名称" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="业务类型" prop="businessType">
                                    <el-select v-model="formData.businessType" placeholder="请选择下拉选择" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="dict in dict.type.business_type" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="采购方式" prop="planMethod">
                                    <el-select v-model="formData.planMethod" placeholder="请选择下拉选择" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="dict in dict.type.purchase_method" :label="dict.label"
                                            :value="dict.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="预算(含税)" prop="planBudget">
                                    <el-input v-model="formData.planBudget" placeholder="请输入含税预算" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="供应商" prop="hId">
                                    <el-select v-model="formData.hId" placeholder="请选择供应商" clearable
                                        :style="{ width: '100%' }">
                                        <el-option v-for="dict in supplierList" :label="dict.h_name"
                                            :value="dict.hid"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="创建人" prop="planFounder">
                                    <el-input v-model="formData.planFounder" disabled placeholder="根据登录用户生成" clearable
                                        :style="{ width: '100%' }">
                                    </el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="创建部门" prop="deptId">
                                    <el-select v-model="formData.deptId" disabled placeholder="根据登录用户部门生成"
                                        :style="{ width: '100%' }">
                                        <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName"
                                            :value="dept.deptId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="15">
                                <el-form-item label="上传文件">
                                    <!-- 这里上传成功后会绑定文件名到formData.fileName字段传给后端的新增接口，uploadDeviceFile定义上传请求，
                        :before-upload是上传前的回调，用于文件格式校验 -->
                                    <el-upload class="upload-demo" action="#" :http-request="uploadDeviceFile"
                                        :drag="true" :before-upload="uploadFileFun" :file-list="formData.fileList"
                                        :on-remove="handleRemoveFile">
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                        <div class="el-upload__tip fontSize12 colorRed" slot="tip">
                                            上传文件格式为word或pdf或png或者txt，文件大小在10M以内</div>
                                    </el-upload>
                                </el-form-item>
                            </el-col>

                            <el-col :span="20">
                                <el-form-item label="备注" prop="comments">
                                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
                                        v-model="formData.comments">
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-form>
                    </el-row>
                </div>
            </div>
        </div>
        <!-- 基本信息录入结束 -->
        <!-- 行项目开始 -->
        <div class="baseInfo">
            <div class="firHeader">
                <p>物料信息</p>
            </div>
            <el-divider></el-divider>
            <div class="material-actions">
                <el-button-group>
                    <el-button type="primary" icon="el-icon-plus" @click="productList"></el-button>
                </el-button-group>
            </div>
            <div class="material-table">
                <el-table :data="deviceForm" style="width: 100%">
                    <el-table-column fixed la bel="序号" width="100" align="center">
                        <template slot-scope="scope">
                            <!-- 动态生成从1开始的序列号 -->
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="vCode" label="行项目编号" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vCode" size="small" disabled placeholder="自动生成"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="tId" label="物料编号" width="130" align="center"></el-table-column>


                    <el-table-column prop="vCount" label="数量" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input-number size="mini" :min="1" v-model="scope.row.vCount"
                                @input="handleInput(scope.row, $event)"> </el-input-number>
                        </template>
                    </el-table-column>

                    <el-table-column prop="taxRate" label="税率" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.csDevice.taxRate" size="small" disabled></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="tUnit" label="单位" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.csDevice.tUnit" size="small" disabled></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="tPrice" label="单价" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.csDevice.tPrice" size="small" disabled></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column prop="totalPrice" label="总价" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.csDevice.totalPrice" size="small" disabled></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vPerson" label="采购人" width="140" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vPerson" size="small" placeholder="输入采购人"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vDeliveryTime" label="交付时间" width="230" align="center">
                        <template slot-scope="scope">
                            <div class="block">
                                <el-date-picker v-model="scope.row.vDeliveryTime" size="small" type="datetime"
                                    placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vDeliveryArea" label="交付地点" width="150" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vDeliveryArea" size="small" placeholder="输入交付地点"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="vIllustrate" label="需求说明" width="150" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.vIllustrate" size="small" placeholder="输入需求说明"></el-input>
                        </template>
                    </el-table-column>

                    <el-table-column fixed="right" label="操作" width="120" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="deleteDeviceRow(scope.row)" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <!-- 行项目开始 -->


        <!-- 产品列表弹窗开始 -->
        <el-dialog title="产品查询" :visible.sync="dialogTableVisible2">
            <div class="productSearch">
                <div style="width: 100%;display: flex; align-items: center; gap:10px;margin-left: 5%;">
                    产品编码: <el-input placeholder="请输入产品编码" style="width: 30%;" v-model="queryParams.tId"
                        clearable></el-input>
                    产品名称: <el-input placeholder="请输入产品名称" style="width: 30%;" v-model="queryParams.tName"
                        clearable></el-input>
                    <el-button type="primary" size="small" @click="searchProjectButton"
                        style="margin-top: 10px; margin-bottom: 10px;margin-left: 30px;">搜索</el-button>
                </div>
            </div>

            <div style="margin-left: 40px;">
                <el-table ref="multipleTable" border :data="productDialogList" tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="tId" header-align="center" label="产品编码"></el-table-column>
                    <el-table-column prop="tName" header-align="center" label="产品名称"></el-table-column>
                </el-table>
                <el-button class="sureDevice" type="primary" round style="margin: 10px auto -10px 88%;"
                    @click="addSelectedToTableList">确定</el-button>

                <div class="pageArea">
                    <div class="pageButton" style="margin-left: auto;">
                        <pagination v-show="true" :total="total" :auto-scroll="false" :page.sync="queryParams.pageNum"
                            :limit.sync="queryParams.pageSize" @pagination="getPageproductList" />
                    </div>
                </div>
            </div>
        </el-dialog>
        <!-- 产品列表弹窗结束 -->

        <div class="formSubmit">
            <el-button type="primary" @click="submitAllForm">提交</el-button>
            <el-button @click="cancel">取消</el-button>
        </div>
        <!-- 留白 -->
        <div class="liubai">

        </div>
    </div>
</template>

<script>
import { getProductList, uplodaBudgetFile, removeFile, submitFrameworkPlan, getFramePlanByPlanCode, editFramePlan, getSupplierList } from '@/api/system/purchase'
import { listDept } from "@/api/system/dept";

export default {

    dicts: ["business_type", "purchase_method"],
    data() {
        return {
            title: '新增框架计划',//标题
            deptList: [],
            formData: {
                planCode: '',
                planName: '',
                planMethod: '',
                planBudget: null,
                hId: null,
                createBy: '',
                businessType: null,
                comments: '',
                fileList: [],
            },
            dialogTableVisible2: false,//物料弹窗
            total: 0,//弹窗总数量
            productDialogList: [],//弹窗行项目
            deviceForm: [

            ],
            supplierList: [],
            baseRules: {
                planName: [
                    { required: true, message: '请输入框架计划名称', trigger: 'blur' }
                ],
                businessType: [
                    { required: true, message: '请选择业务类型', trigger: 'change' }
                ],
                planMethod: [
                    { required: true, message: '请选择采购方式', trigger: 'change' }
                ],
                planBudget: [
                    { required: true, message: '请输入含税预算', trigger: 'blur' }
                ],
                hId: [
                    { required: true, message: '请选择供应商', trigger: 'change' }
                ]
            },
            selectedProducts: [], // 保存选中的产品
            queryParams: {
                tId: null,
                tName: '',
                pageNum: 1,
                pageSize: 10,
            },
        }
    },
    methods: {
        //删除行项目
        deleteDeviceRow(row) {
            this.deviceForm = this.deviceForm.filter(item => item !== row);
        },
        //删除文件
        handleRemoveFile(file) {
            removeFile(file.name).then(res => {

                if (res.data == 1) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                }
                const index = this.formData.fileList.findIndex(f => f.name === file.name);
                this.formData.fileList.splice(index, 1); // 从 fileList 中移除一个元素，从 index 位置开始
                console.log(this.formData.fileList, "1231231");

            })
        },
        //查询物料信息
        getPageproductList() {
            this.productList();
        },
        cancel() {

        },
        //文件上传前的校验
        uploadFileFun(file) {
            var test = /(doc|docx|pdf|txt|png)$/.test(file.name.split('.').pop().toLowerCase());
            if (!test) {
                this.$message.error("请上传正确的文档格式!");
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                this.$message.error("上传文件大小不能超过 10MB!");
                return false;
            }
        },
        uploadDeviceFile(file) {
            // 创建formdata实例
            let formData = new window.FormData();
            // 将获取的文件通过append方法加入实例中
            formData.append("file", file.file);
            //发送axios请求
            uplodaBudgetFile(formData)
                .then(res => {
                    // 拿到后端响应的文件名称反显到列表的form
                    const fileInfo = {
                        name: res.data.name,
                        url: res.data.url,
                        size: res.data.size,
                        uid: file.file.uid,
                    };
                    this.formData.fileList.push(fileInfo); // 直接添加文件名字符串    
                })
                .catch(err => {
                    console.error('上传文件失败:', err);
                });
        },
        //查询物料列表
        productList() {
            this.dialogTableVisible2 = true;
            let params = { ...this.queryParams };
            getProductList(params).then(response => {
                this.productDialogList = response.rows;
                this.total = response.total;
                this.$nextTick(() => {
                    if (this.$refs.multipleTable) {
                        this.$refs.multipleTable.doLayout();
                    }
                });
            });
        },
        addSelectedToTableList() {
            this.deviceForm.forEach((eles) => {
                this.selectedProducts.forEach((ele, index) => {
                    if (eles.tId === ele.tId) {
                        this.selectedProducts.splice(index, 1);
                        this.$message({
                            message: '该物料已存在',
                            type: 'warning'
                        });
                    }
                })

            })
            this.selectedProducts.forEach((ele) => {
                // 创建一个新的 csDevice 对象
                ele.csDevice = {
                    tPrice: ele.tPrice,
                    tUnit: ele.tUnit,
                    taxRate: ele.taxRate,
                };
            });

            // 为每行的vCount设置默认值1  
            this.deviceForm.push(...this.selectedProducts)
            this.deviceForm.forEach((eles) => {
                this.$set(eles, 'vCount', 1); // 确保 vCount 是反应的  
                this.$set(eles.csDevice, 'totalPrice', eles.csDevice.tPrice); // 确保 vCount 是反应的  
            })
            this.selectedProducts = []; // 清空选中的产品
            this.$refs.multipleTable.clearSelection(); // 清除表格的选择状态
            this.dialogTableVisible2 = false;
        },
        handleSelectionChange(val) {
            this.selectedProducts = val;
        },
        //条件搜索物料(产品)
        searchProjectButton() {
            this.productList();
        },
        // 添加或修改
        submitAllForm() {
            const allForm = {
                "framePlan": this.formData,
                "lineItems": this.deviceForm,
            }
            if (this.title == "修改框架计划") {
                editFramePlan(allForm).then(res => {
                    if (res.data > 0) {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                        this.$router.push('/purchase/frameworkPlan/index')
                    }
                }).catch(err => {

                })
            } else {
                this.$refs.elForm.validate((valid) => {
                    if (valid) {
                        submitFrameworkPlan(allForm).then((res) => {
                            this.formData = {};
                            this.deviceForm = [];
                            this.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            this.$router.push('/purchase/frameworkPlan/index');
                        }).catch(() => {
                            this.$modal.msgError("出了点小问题,请重试!")
                        });
                    } else {
                        this.$modal.msgError("请填写完整!!!")
                    }
                });
            }


        },
        //数量值的改变
        handleInput(row, value) {
            row.csDevice.totalPrice = value * row.csDevice.tPrice + value * row.csDevice.tPrice * row.csDevice.taxRate
        },
        //路由参数判断(新增或修改)
        judgeQueryValue() {
            //供应商列表
            getSupplierList().then(res => {
                if (res.data.length > 0) {
                    this.supplierList = res.data;
                }
            })
            if (!this.formData.planCode == "") {
                this.title = "修改框架计划";
                //后端获取数据
                getFramePlanByPlanCode(this.formData.planCode).then(res => {
                    this.formData = res.framePlan;
                    this.formData.planMethod = this.formData.planMethod.toString();
                    this.deviceForm = res.lineItems;
                    console.log(res, "奋斗啥方式");

                })
            }
        },
        //部门列表
        getDeptList() {
            listDept().then((res) => {
                console.log(res,"收复失第三方顺丰速递发");
                this.deptList = res.data; // 将获取的数据赋值给 deptList
            });
        }
    },
    mounted() {
        this.formData.planCode = this.$route.query.planCode;
        this.judgeQueryValue();
        this.getDeptList();

    },

}
</script>


<style>
.bigBox {
    height: auto;
}

.baseInfo {
    width: 80%;
    margin-top: 3%;
    margin-left: 10%;
    font-weight: 100;
    /* 使文字更细 */
    font-size: 24px;
    /* 使文字更大 */
    text-align: center;
    /* 使内部文字居中 */
    justify-content: center;
    /* 水平居中 */
    border: 0.2px solid rgb(211, 209, 209);
    /* 黑色0.2边框 */
    box-shadow: -5px 5px 5px -5px rgba(0, 0, 0, 0.75);
    /* 左阴影 */
    padding: 10px;
    /* 可选：添加一些内边距 */
}

.material-actions {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    margin-bottom: 10px;
    /* 根据需要调整间距 */
}

/* .content {
    padding-left: 4%;
} */

.upload-demo {
    margin-right: 230px;
}

.liubai {
    height: 100px;
}

.formSubmit {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    /* 将子元素推到右侧 */
    gap: 5px;
    /* 调整按钮之间的间距 */
    padding-top: 30px;
    padding-right: 10%;
    /* 向左移动按钮的距离 */
}
</style>